package com.jiangjiang.eshop.promotion.task;

import com.jiangjiang.eshop.common.help.DateHelper;
import com.jiangjiang.eshop.promotion.constant.PromotionActivityStatus;
import com.jiangjiang.eshop.promotion.domain.PromotionActivityEntity;
import com.jiangjiang.eshop.promotion.service.PromotionActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName PromotionActivityStatusCheckTask
 * @Description TODO
 * @Author jhw
 * @Date 2021/8/2 14:56
 * @Version 1.0
 **/
@Slf4j
@Component
public class PromotionActivityStatusCheckTask {

    @Autowired
    private PromotionActivityService promotionActivityService;
    @Autowired
    private DateHelper dateHelper;

    /**
     * 每日0点执行一次，营销活动 -> 日级别
     * @throws ParseException
     */
    @Scheduled(cron = "0 0 0 1/1 * ?")
    public void execute() throws ParseException {
        Date currentDate = dateHelper.getCurrentDate();
        List<PromotionActivityEntity> enableEntityList = promotionActivityService.queryAllNeedEnablePromotionActivity(currentDate);
        this.updateStatus(enableEntityList, PromotionActivityStatus.ENABLED);

        List<PromotionActivityEntity> disabledEntityList = promotionActivityService.queryAllNeedDisabledPromotionActivity(currentDate);
        this.updateStatus(disabledEntityList, PromotionActivityStatus.DISABLED);

    }

    /**
     * 耿欣营销活动状态
     *
     * @param entityList 营销活动
     * @param status 需要更新的状态
     */
    private void updateStatus(List<PromotionActivityEntity> entityList, Integer status) {
        List<PromotionActivityEntity> entities = entityList.stream().peek(entity -> entity.setStatus(status)).collect(Collectors.toList());
        promotionActivityService.updateBatchById(entities);
    }
}
